<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心 - 新商城</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <header class="bg-white shadow-md">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="text-2xl font-bold text-blue-600">新商城</div>
            <div class="flex items-center space-x-6">
                <div class="relative">
                    <button id="userMenuBtn" class="flex items-center space-x-2 focus:outline-none">
                        <i class="fa fa-user-circle text-xl text-gray-600"></i>
                        <span id="usernameDisplay" class="text-gray-700"></span>
                        <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                    </button>
                    <div id="userMenu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 hidden z-10">
                        <a href="#" id="editProfileBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                            <i class="fa fa-edit mr-2"></i>编辑资料
                        </a>
                        <a href="#" id="logoutBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                            <i class="fa fa-sign-out mr-2"></i>退出登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <div class="flex flex-col md:flex-row gap-6">
            <!-- 侧边导航 -->
            <div class="w-full md:w-64 bg-white rounded-lg shadow-md p-4">
                <nav class="space-y-1">
                    <a href="#" class="nav-link active block px-4 py-3 rounded-md bg-blue-50 text-blue-600 font-medium">
                        <i class="fa fa-home mr-3"></i>首页
                    </a>
                    <a href="#" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-shopping-bag mr-3"></i>商品列表
                    </a>
                    <a href="#" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-shopping-cart mr-3"></i>我的订单
                    </a>
                    <a href="#" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-gift mr-3"></i>我的商品
                    </a>
                </nav>
            </div>

            <!-- 主内容区 -->
            <div class="flex-1 space-y-6">
                <!-- 欢迎信息 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-2xl font-bold mb-2">欢迎回来，<span id="welcomeUsername"></span>！</h2>
                    <p class="text-gray-600">在这里可以浏览和购买商品</p>
                </div>

                <!-- 商品列表 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold">商品列表</h2>
                    </div>
                    
                    <div id="goodsList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <!-- 商品将通过JavaScript动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 购买商品模态框 -->
    <div id="buyModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">购买商品</h3>
                <button id="closeModalBtn" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <div id="modalContent" class="mb-4">
                <p><strong>商品名称：</strong><span id="modalGoodName"></span></p>
                <p><strong>价格：</strong>¥<span id="modalGoodPrice"></span></p>
                <p><strong>描述：</strong><span id="modalGoodDesc"></span></p>
            </div>
            
            <button id="confirmBuyBtn" class="w-full py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition">
                确认购买
            </button>
        </div>
    </div>

    <!-- 编辑资料模态框 -->
    <div id="editProfileModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">编辑个人资料</h3>
                <button id="closeEditModalBtn" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <form id="editProfileForm" class="space-y-4">
                <input type="hidden" id="editUserId">
                
                <div>
                    <label for="editUsername" class="block text-gray-700 mb-1">用户名</label>
                    <input type="text" id="editUsername" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editPassword" class="block text-gray-700 mb-1">密码 (不修改请留空)</label>
                    <input type="password" id="editPassword" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editNickname" class="block text-gray-700 mb-1">昵称</label>
                    <input type="text" id="editNickname" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editPhone" class="block text-gray-700 mb-1">手机号</label>
                    <input type="tel" id="editPhone" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editAddress" class="block text-gray-700 mb-1">地址</label>
                    <input type="text" id="editAddress" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editEmail" class="block text-gray-700 mb-1">邮箱</label>
                    <input type="email" id="editEmail" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <button type="submit" class="w-full py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition">
                    保存修改
                </button>
            </form>
        </div>
    </div>

    <footer class="bg-gray-800 text-white py-8 mt-16">
        <div class="container mx-auto px-4 text-center">
            <p>© 2025 新商城 版权所有</p>
        </div>
    </footer>

    <script>
        // 当前登录用户信息
        let currentUser = null;
        // 当前选中的商品
        let selectedGood = null;

        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', async () => {
            // 检查登录状态
            const userStr = localStorage.getItem('user');
            if (!userStr) {
                window.location.href = 'user-login.html';
                return;
            }
            
            currentUser = JSON.parse(userStr);
            
            // 显示用户名
            document.getElementById('usernameDisplay').textContent = currentUser.username;
            document.getElementById('welcomeUsername').textContent = currentUser.nickname || currentUser.username;
            
            // 加载商品列表
            await loadGoodsList();
            
            // 绑定事件
            bindEvents();
        });

        // 绑定事件
        function bindEvents() {
            // 用户菜单切换
            document.getElementById('userMenuBtn').addEventListener('click', () => {
                document.getElementById('userMenu').classList.toggle('hidden');
            });
            
            // 点击其他区域关闭用户菜单
            document.addEventListener('click', (e) => {
                const userMenuBtn = document.getElementById('userMenuBtn');
                const userMenu = document.getElementById('userMenu');
                
                if (!userMenuBtn.contains(e.target) && !userMenu.contains(e.target)) {
                    userMenu.classList.add('hidden');
                }
            });
            
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', () => {
                localStorage.removeItem('user');
                window.location.href = 'index.html';
            });
            
            // 编辑资料按钮
            document.getElementById('editProfileBtn').addEventListener('click', () => {
                fillEditProfileForm();
                document.getElementById('editProfileModal').classList.remove('hidden');
            });
            
            // 关闭编辑资料模态框
            document.getElementById('closeEditModalBtn').addEventListener('click', () => {
                document.getElementById('editProfileModal').classList.add('hidden');
            });
            
            // 关闭购买模态框
            document.getElementById('closeModalBtn').addEventListener('click', () => {
                document.getElementById('buyModal').classList.add('hidden');
            });
            
            // 编辑资料表单提交
            document.getElementById('editProfileForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                await submitEditProfile();
            });
            
            // 确认购买按钮
            document.getElementById('confirmBuyBtn').addEventListener('click', async () => {
                await confirmPurchase();
            });
            
            // 导航链接切换
            document.querySelectorAll('.nav-link').forEach(link => {
                link.addEventListener('click', async(e) => {
                    e.preventDefault();
                    
                    // 移除所有active类
                    document.querySelectorAll('.nav-link').forEach(l => {
                        l.classList.remove('active', 'bg-blue-50', 'text-blue-600');
                        l.classList.add('text-gray-700');
                    });
                    
                    // 给当前点击的添加active类
                    e.target.classList.add('active', 'bg-blue-50', 'text-blue-600');
                    e.target.classList.remove('text-gray-700');
                    
                    // 根据点击的导航切换内容
                    const text = e.target.textContent.trim();
                    if (text.includes('商品列表')) {
                        await loadGoodsList();
                    } else if (text.includes('我的订单')) {
                        await loadMyOrders();
                    } else if (text.includes('我的商品')) {
                        await loadMyGoods();
                    } else if (text.includes('首页')) {
                        await loadGoodsList();
                    }
                });
            });
        }

        // 加载商品列表
        async function loadGoodsList() {
            try {
                const response = await fetch('http://localhost:8080/api/goods/all-with-merchant');
                const result = await response.json();
                
                if (result.success && result.data) {
                    const goodsListElement = document.getElementById('goodsList');
                    goodsListElement.innerHTML = '';
                    
                    result.data.forEach(good => {
                        // 创建商品卡片
                        const goodCard = document.createElement('div');
                        goodCard.className = 'border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition';
                        goodCard.innerHTML = `
                            <div class="p-4">
                                <h3 class="font-bold text-lg mb-2">${good.goodname}</h3>
                                <!-- 新增商家名称及链接 -->
                                <p class="text-blue-600 text-sm mb-1">
                                    <a href="merchant-page.html?merchantId=${good.merchantId}" class="hover:underline">
                                        商家: ${good.merchantName}
                                    </a>
                                </p>
                                <p class="text-gray-600 text-sm mb-2">${good.good_desc || '无描述'}</p>
                                <p class="text-red-600 font-bold mb-4">¥${(good.price / 100).toFixed(2)}</p>
                                <button class="buy-btn w-full py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition" 
                                    data-goodid="${good.goodid}">
                                立即购买
                            </button>
                        </div>
    `;
    goodsListElement.appendChild(goodCard);
});
                    
                    // 绑定购买按钮事件
                    document.querySelectorAll('.buy-btn').forEach(btn => {
                        btn.addEventListener('click', () => {
                            const goodId = btn.getAttribute('data-goodid');
                            const good = result.data.find(g => g.goodid == goodId);
                            openBuyModal(good);
                        });
                    });
                }
            } catch (error) {
                console.error('加载商品失败:', error);
                alert('加载商品失败，请稍后重试');
            }
        }

        // 打开购买模态框
        function openBuyModal(good) {
            selectedGood = good;
            
            document.getElementById('modalGoodName').textContent = good.goodname;
            document.getElementById('modalGoodPrice').textContent = (good.price / 100).toFixed(2);
            document.getElementById('modalGoodDesc').textContent = good.good_desc || '无描述';
            
            document.getElementById('buyModal').classList.remove('hidden');
        }

        // 确认购买
        async function confirmPurchase() {
            if (!selectedGood || !currentUser) return;
            
            try {
                // 创建订单数据
                const orderData = {
                    senderid: 0, // 商家ID会在后端处理
                    receiverid: currentUser.id,
                    goodid: selectedGood.goodid,
                    goodname: selectedGood.goodname,
                    price: selectedGood.price
                };
                
                // 创建所有权转移数据
                const ownershipData = {
                    goodid: selectedGood.goodid,
                    userid: currentUser.id,
                    userkind: 1 // 用户
                };
                
                const response = await fetch('http://localhost:8080/api/orders/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        order: orderData,
                        ownership: ownershipData
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('购买成功！');
                    document.getElementById('buyModal').classList.add('hidden');
                    // 刷新商品列表
                    await loadGoodsList();
                } else {
                    alert('购买失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('购买商品失败:', error);
                alert('购买商品失败，请稍后重试');
            }
        }

        // 加载我的订单
        async function loadMyOrders() {
            try {
                const response = await fetch('http://localhost:8080/api/orders/user/owned', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(currentUser)
                });
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const goodsListElement = document.getElementById('goodsList');
                    goodsListElement.innerHTML = '';
                    
                    if (result.data.length === 0) {
                        goodsListElement.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">您暂无订单</div>';
                        return;
                    }
                    
                    result.data.forEach(order => {
                        const orderCard = document.createElement('div');
                        orderCard.className = 'border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition';
                        orderCard.innerHTML = `
                            <div class="p-4">
                                <div class="flex justify-between items-start mb-2">
                                    <h3 class="font-bold text-lg">订单 #${order.id}</h3>
                                    <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded">已完成</span>
                                </div>
                                <p class="text-gray-700 mb-1">商品: ${order.goodname}</p>
                                <p class="text-gray-700 mb-1">价格: ¥${order.price}</p>
                                <p class="text-gray-500 text-sm mt-2">下单时间: ${order.createtime ? new Date(order.createtime).toLocaleString('zh-CN', { 
                                    year: 'numeric', 
                                    month: '2-digit', 
                                    day: '2-digit', 
                                    hour: '2-digit', 
                                    minute: '2-digit', 
                                    second: '2-digit' 
                                }) : '未知'}</p>
                            </div>
                        `;
                        goodsListElement.appendChild(orderCard);
                    });
                }
            } catch (error) {
                console.error('加载订单失败:', error);
                alert('加载订单失败，请稍后重试');
            }
        }

        // 验证昵称长度（≤7个字符）
    function validateNickname(nickname) {
        if (nickname.length > 7) {
            return "昵称长度不能超过7个字符";
        }
        return null;
    }

    // 验证手机号（11位数字，符合国内规则）
    function validatePhone(phone) {
        const reg = /^1[3-9]\d{9}$/;
        if (!reg.test(phone)) {
            return "手机号格式错误（需11位有效数字）";
        }
        return null;
    }

    // 验证邮箱格式
    function validateEmail(email) {
        if (!email) return null; // 非必填项
        const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (!reg.test(email)) {
            return "邮箱格式错误（例如：xxx@xxx.com）";
        }
        return null;
    }

        // 加载我的商品
        async function loadMyGoods() {
            try {
                const response = await fetch('http://localhost:8080/api/goods/owned', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(currentUser)
                });
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const goodsListElement = document.getElementById('goodsList');
                    goodsListElement.innerHTML = '';
                    
                    if (result.data.length === 0) {
                        goodsListElement.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">您暂无已购买的商品</div>';
                        return;
                    }
                    
                    result.data.forEach(good => {
                        const goodCard = document.createElement('div');
                        goodCard.className = 'border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition';
                        goodCard.innerHTML = `
                            <div class="p-4">
                                <h3 class="font-bold text-lg mb-2">${good.goodname}</h3>
                                <p class="text-gray-600 text-sm mb-2">${good.good_desc || '无描述'}</p>
                                <p class="text-red-600 font-bold">¥${(good.price / 100).toFixed(2)}</p>
                            </div>
                        `;
                        goodsListElement.appendChild(goodCard);
                    });
                }
            } catch (error) {
                console.error('加载我的商品失败:', error);
                alert('加载我的商品失败，请稍后重试');
            }
        }

        // 填充编辑资料表单
        function fillEditProfileForm() {
            document.getElementById('editUserId').value = currentUser.id;
            document.getElementById('editUsername').value = currentUser.username || '';
            document.getElementById('editNickname').value = currentUser.nickname || '';
            document.getElementById('editPhone').value = currentUser.phone || '';
            document.getElementById('editAddress').value = currentUser.address || '';
            document.getElementById('editEmail').value = currentUser.email || '';
            document.getElementById('editPassword').value = ''; // 密码不显示
        }

        // 提交编辑资料
        async function submitEditProfile() {

             // 获取表单数据
        const nickname = document.getElementById('editNickname').value;
        const phone = document.getElementById('editPhone').value;
        const email = document.getElementById('editEmail').value;
        
        // 执行验证
        const nicknameError = validateNickname(nickname);
        const phoneError = validatePhone(phone);
        const emailError = validateEmail(email);
        
        if (nicknameError) {
            alert(nicknameError);
            return;
        }
        if (phoneError) {
            alert(phoneError);
            return;
        }
        if (emailError) {
            alert(emailError);
            return;
        }



            const userData = {
                id: document.getElementById('editUserId').value,
                username: document.getElementById('editUsername').value,
                nickname: document.getElementById('editNickname').value,
                phone: document.getElementById('editPhone').value,
                address: document.getElementById('editAddress').value,
                email: document.getElementById('editEmail').value
            };
            
            // 只有输入了密码才更新密码
            const password = document.getElementById('editPassword').value;
            if (password) {
                userData.password = password;
            }
            
            try {
                const response = await fetch('http://localhost:8080/api/user/update', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(userData)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 更新本地存储的用户信息
                    currentUser = { ...currentUser, ...userData };
                    localStorage.setItem('user', JSON.stringify(currentUser));
                    
                    // 更新页面显示
                    document.getElementById('usernameDisplay').textContent = currentUser.username;
                    document.getElementById('welcomeUsername').textContent = currentUser.nickname || currentUser.username;
                    
                    alert('资料更新成功');
                    document.getElementById('editProfileModal').classList.add('hidden');
                } else {
                    alert('资料更新失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('更新资料失败:', error);
                alert('更新资料失败，请稍后重试');
            }
        }
    </script>
</body>
</html>